import { asyncRoutes, constantRoutes } from '@/router'
import store from '..'

/**
 * 判断该权限是否有权限操作该项目
 * @param roles
 * @param route
 */
function hasPermission(roles, route, routerAccess) {
  for (const idx in routerAccess) {
    const access = routerAccess[idx]
    if (route.name && access.title === route.name) {
      route.meta.roles = access.roles
      break
    }
  }
  // console.log(route.meta.roles)
  if (route.meta && route.meta.roles) {
    return route.meta.roles.includes(roles)
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 * @param routerAccess
 */
export function filterAsyncRoutes(routes, roles, routerAccess) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp, routerAccess)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles, routerAccess)
      }
      res.push(tmp)
    }
  })
  return res
}

export function showAsyncRoutes(routes) {
  if (store.getters.lineNumber !== null && store.getters.lineNumber !== '') {
    routes.forEach(route => {
      route.hidden = false
    })
  }
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, info) {
    return new Promise(resolve => {
      const { roleKey, routerAccess } = info
      let accessedRoutes
      if (roleKey.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        // console.log(asyncRoutes)
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roleKey, routerAccess)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
